<?php

/**
 * 
 *
 * @version 1.107
 * @package entity
 */
class AlaniaUsuarioModel extends Db2PhpEntityBase implements Db2PhpEntityModificationTracking {

    private static $CLASS_NAME = 'AlaniaUsuarioModel';

    const SQL_IDENTIFIER_QUOTE = '`';
    const SQL_TABLE_NAME = 'alania_usuario';
    const SQL_INSERT = 'INSERT INTO `alania_usuario` (`id_usuario`,`identificacion`,`nombre`,`apellido`,`password`,`sessionkey`,`last_seen`,`sexo`) VALUES (?,?,?,?,?,?,?,?)';
    const SQL_INSERT_AUTOINCREMENT = 'INSERT INTO `alania_usuario` (`identificacion`,`nombre`,`apellido`,`password`,`sessionkey`,`last_seen`,`sexo`) VALUES (?,?,?,?,?,?,?)';
    const SQL_UPDATE = 'UPDATE `alania_usuario` SET `id_usuario`=?,`identificacion`=?,`nombre`=?,`apellido`=?,`password`=?,`sessionkey`=?,`last_seen`=?,`sexo`=? WHERE `id_usuario`=?';
    const SQL_SELECT_PK = 'SELECT * FROM `alania_usuario` WHERE `id_usuario`=?';
    const SQL_DELETE_PK = 'DELETE FROM `alania_usuario` WHERE `id_usuario`=?';
    const FIELD_ID_USUARIO = -362264903;
    const FIELD_IDENTIFICACION = -1736735922;
    const FIELD_NOMBRE = -38540808;
    const FIELD_APELLIDO = 1102825293;
    const FIELD_PASSWORD = 1455129866;
    const FIELD_SESSIONKEY = -1409878344;
    const FIELD_LAST_SEEN = 805807605;
    const FIELD_SEXO = 974400184;

    private static $PRIMARY_KEYS = array(self::FIELD_ID_USUARIO);
    private static $AUTOINCREMENT_FIELDS = array(self::FIELD_ID_USUARIO);
    private static $FIELD_NAMES = array(
        self::FIELD_ID_USUARIO => 'id_usuario',
        self::FIELD_IDENTIFICACION => 'identificacion',
        self::FIELD_NOMBRE => 'nombre',
        self::FIELD_APELLIDO => 'apellido',
        self::FIELD_PASSWORD => 'password',
        self::FIELD_SESSIONKEY => 'sessionkey',
        self::FIELD_LAST_SEEN => 'last_seen',
        self::FIELD_SEXO => 'sexo');
    private static $PROPERTY_NAMES = array(
        self::FIELD_ID_USUARIO => 'idUsuario',
        self::FIELD_IDENTIFICACION => 'identificacion',
        self::FIELD_NOMBRE => 'nombre',
        self::FIELD_APELLIDO => 'apellido',
        self::FIELD_PASSWORD => 'password',
        self::FIELD_SESSIONKEY => 'sessionkey',
        self::FIELD_LAST_SEEN => 'lastSeen',
        self::FIELD_SEXO => 'sexo');
    private static $PROPERTY_TYPES = array(
        self::FIELD_ID_USUARIO => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_IDENTIFICACION => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_NOMBRE => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_APELLIDO => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_PASSWORD => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_SESSIONKEY => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_LAST_SEEN => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_SEXO => Db2PhpEntity::PHP_TYPE_STRING);
    private static $FIELD_TYPES = array(
        self::FIELD_ID_USUARIO => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_IDENTIFICACION => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 45, 0, false),
        self::FIELD_NOMBRE => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 45, 0, false),
        self::FIELD_APELLIDO => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 45, 0, false),
        self::FIELD_PASSWORD => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 255, 0, false),
        self::FIELD_SESSIONKEY => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 255, 0, true),
        self::FIELD_LAST_SEEN => array(Db2PhpEntity::JDBC_TYPE_TIMESTAMP, 19, 0, true),
        self::FIELD_SEXO => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 1, 0, false));
    private static $DEFAULT_VALUES = array(
        self::FIELD_ID_USUARIO => null,
        self::FIELD_IDENTIFICACION => '',
        self::FIELD_NOMBRE => '',
        self::FIELD_APELLIDO => '',
        self::FIELD_PASSWORD => '',
        self::FIELD_SESSIONKEY => null,
        self::FIELD_LAST_SEEN => null,
        self::FIELD_SEXO => '');
    private $idUsuario;
    private $identificacion;
    private $nombre;
    private $apellido;
    private $password;
    private $sessionkey;
    private $lastSeen;
    private $sexo;

    /**
     * set value for id_usuario 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @param mixed $idUsuario
     * @return AlaniaUsuarioModel
     */
    public function &setIdUsuario($idUsuario) {
        $this->notifyChanged(self::FIELD_ID_USUARIO, $this->idUsuario, $idUsuario);
        $this->idUsuario = $idUsuario;
        return $this;
    }

    /**
     * get value for id_usuario 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @return mixed
     */
    public function getIdUsuario() {
        return $this->idUsuario;
    }

    /**
     * set value for identificacion 
     *
     * type:VARCHAR,size:45,default:null,unique
     *
     * @param mixed $identificacion
     * @return AlaniaUsuarioModel
     */
    public function &setIdentificacion($identificacion) {
        $this->notifyChanged(self::FIELD_IDENTIFICACION, $this->identificacion, $identificacion);
        $this->identificacion = $identificacion;
        return $this;
    }

    /**
     * get value for identificacion 
     *
     * type:VARCHAR,size:45,default:null,unique
     *
     * @return mixed
     */
    public function getIdentificacion() {
        return $this->identificacion;
    }

    /**
     * set value for nombre 
     *
     * type:VARCHAR,size:45,default:null,index
     *
     * @param mixed $nombre
     * @return AlaniaUsuarioModel
     */
    public function &setNombre($nombre) {
        $this->notifyChanged(self::FIELD_NOMBRE, $this->nombre, $nombre);
        $this->nombre = $nombre;
        return $this;
    }

    /**
     * get value for nombre 
     *
     * type:VARCHAR,size:45,default:null,index
     *
     * @return mixed
     */
    public function getNombre() {
        return $this->nombre;
    }

    /**
     * set value for apellido 
     *
     * type:VARCHAR,size:45,default:null,index
     *
     * @param mixed $apellido
     * @return AlaniaUsuarioModel
     */
    public function &setApellido($apellido) {
        $this->notifyChanged(self::FIELD_APELLIDO, $this->apellido, $apellido);
        $this->apellido = $apellido;
        return $this;
    }

    /**
     * get value for apellido 
     *
     * type:VARCHAR,size:45,default:null,index
     *
     * @return mixed
     */
    public function getApellido() {
        return $this->apellido;
    }

    /**
     * set value for password 
     *
     * type:VARCHAR,size:255,default:null
     *
     * @param mixed $password
     * @return AlaniaUsuarioModel
     */
    public function &setPassword($password) {
        $this->notifyChanged(self::FIELD_PASSWORD, $this->password, $password);
        $this->password = $password;
        return $this;
    }

    /**
     * get value for password 
     *
     * type:VARCHAR,size:255,default:null
     *
     * @return mixed
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * set value for sessionkey 
     *
     * type:VARCHAR,size:255,default:null,nullable
     *
     * @param mixed $sessionkey
     * @return AlaniaUsuarioModel
     */
    public function &setSessionkey($sessionkey) {
        $this->notifyChanged(self::FIELD_SESSIONKEY, $this->sessionkey, $sessionkey);
        $this->sessionkey = $sessionkey;
        return $this;
    }

    /**
     * get value for sessionkey 
     *
     * type:VARCHAR,size:255,default:null,nullable
     *
     * @return mixed
     */
    public function getSessionkey() {
        return $this->sessionkey;
    }

    /**
     * set value for last_seen 
     *
     * type:DATETIME,size:19,default:null,nullable
     *
     * @param mixed $lastSeen
     * @return AlaniaUsuarioModel
     */
    public function &setLastSeen($lastSeen) {
        $this->notifyChanged(self::FIELD_LAST_SEEN, $this->lastSeen, $lastSeen);
        $this->lastSeen = $lastSeen;
        return $this;
    }

    /**
     * get value for last_seen 
     *
     * type:DATETIME,size:19,default:null,nullable
     *
     * @return mixed
     */
    public function getLastSeen() {
        return $this->lastSeen;
    }

    /**
     * set value for sexo 
     *
     * type:VARCHAR,size:1,default:null
     *
     * @param mixed $sexo
     * @return AlaniaUsuarioModel
     */
    public function &setSexo($sexo) {
        $this->notifyChanged(self::FIELD_SEXO, $this->sexo, $sexo);
        $this->sexo = $sexo;
        return $this;
    }

    /**
     * get value for sexo 
     *
     * type:VARCHAR,size:1,default:null
     *
     * @return mixed
     */
    public function getSexo() {
        return $this->sexo;
    }

    /**
     * Get table name
     *
     * @return string
     */
    public static function getTableName() {
        return self::SQL_TABLE_NAME;
    }

    /**
     * Get array with field id as index and field name as value
     *
     * @return array
     */
    public static function getFieldNames() {
        return self::$FIELD_NAMES;
    }

    /**
     * Get array with field id as index and property name as value
     *
     * @return array
     */
    public static function getPropertyNames() {
        return self::$PROPERTY_NAMES;
    }

    /**
     * get the field name for the passed field id.
     *
     * @param int $fieldId
     * @param bool $fullyQualifiedName true if field name should be qualified by table name
     * @return string field name for the passed field id, null if the field doesn't exist
     */
    public static function getFieldNameByFieldId($fieldId, $fullyQualifiedName = true) {
        if (!array_key_exists($fieldId, self::$FIELD_NAMES)) {
            return null;
        }
        $fieldName = self::SQL_IDENTIFIER_QUOTE . self::$FIELD_NAMES[$fieldId] . self::SQL_IDENTIFIER_QUOTE;
        if ($fullyQualifiedName) {
            return self::SQL_IDENTIFIER_QUOTE . self::SQL_TABLE_NAME . self::SQL_IDENTIFIER_QUOTE . '.' . $fieldName;
        }
        return $fieldName;
    }

    /**
     * Get array with field ids of identifiers
     *
     * @return array
     */
    public static function getIdentifierFields() {
        return self::$PRIMARY_KEYS;
    }

    /**
     * Get array with field ids of autoincrement fields
     *
     * @return array
     */
    public static function getAutoincrementFields() {
        return self::$AUTOINCREMENT_FIELDS;
    }

    /**
     * Get array with field id as index and property type as value
     *
     * @return array
     */
    public static function getPropertyTypes() {
        return self::$PROPERTY_TYPES;
    }

    /**
     * Get array with field id as index and field type as value
     *
     * @return array
     */
    public static function getFieldTypes() {
        return self::$FIELD_TYPES;
    }

    /**
     * Assign default values according to table
     * 
     */
    public function assignDefaultValues() {
        $this->assignByArray(self::$DEFAULT_VALUES);
    }

    /**
     * return hash with the field name as index and the field value as value.
     *
     * @return array
     */
    public function toHash() {
        $array = $this->toArray();
        $hash = array();
        foreach ($array as $fieldId => $value) {
            $hash[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        return $hash;
    }

    /**
     * return array with the field id as index and the field value as value.
     *
     * @return array
     */
    public function toArray() {
        return array(
            self::FIELD_ID_USUARIO => $this->getIdUsuario(),
            self::FIELD_IDENTIFICACION => $this->getIdentificacion(),
            self::FIELD_NOMBRE => $this->getNombre(),
            self::FIELD_APELLIDO => $this->getApellido(),
            self::FIELD_PASSWORD => $this->getPassword(),
            self::FIELD_SESSIONKEY => $this->getSessionkey(),
            self::FIELD_LAST_SEEN => $this->getLastSeen(),
            self::FIELD_SEXO => $this->getSexo());
    }

    /**
     * return array with the field id as index and the field value as value for the identifier fields.
     *
     * @return array
     */
    public function getPrimaryKeyValues() {
        return array(
            self::FIELD_ID_USUARIO => $this->getIdUsuario());
    }

    /**
     * cached statements
     *
     * @var array<string,array<string,PDOStatement>>
     */
    private static $stmts = array();
    private static $cacheStatements = true;

    /**
     * prepare passed string as statement or return cached if enabled and available
     *
     * @param PDO $db
     * @param string $statement
     * @return PDOStatement
     */
    protected static function prepareStatement(PDO $db, $statement) {
        if (self::isCacheStatements()) {
            if (in_array($statement, array(self::SQL_INSERT, self::SQL_INSERT_AUTOINCREMENT, self::SQL_UPDATE, self::SQL_SELECT_PK, self::SQL_DELETE_PK))) {
                $dbInstanceId = spl_object_hash($db);
                if (empty(self::$stmts[$statement][$dbInstanceId])) {
                    self::$stmts[$statement][$dbInstanceId] = $db->prepare($statement);
                }
                return self::$stmts[$statement][$dbInstanceId];
            }
        }
        return $db->prepare($statement);
    }

    /**
     * Enable statement cache
     *
     * @param bool $cache
     */
    public static function setCacheStatements($cache) {
        self::$cacheStatements = true == $cache;
    }

    /**
     * Check if statement cache is enabled
     *
     * @return bool
     */
    public static function isCacheStatements() {
        return self::$cacheStatements;
    }

    /**
     * check if this instance exists in the database
     *
     * @param PDO $db
     * @return bool
     */
    public function existsInDatabase(PDO $db) {
        $filter = array();
        foreach ($this->getPrimaryKeyValues() as $fieldId => $value) {
            $filter[] = new DFC($fieldId, $value, DFC::EXACT_NULLSAFE);
        }
        return 0 != count(self::findByFilter($db, $filter, true));
    }

    /**
     * Update to database if exists, otherwise insert
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateInsertToDatabase(PDO $db) {
        if ($this->existsInDatabase($db)) {
            return $this->updateToDatabase($db);
        } else {
            return $this->insertIntoDatabase($db);
        }
    }

    /**
     * Query by Example.
     *
     * Match by attributes of passed example instance and return matched rows as an array of AlaniaUsuarioModel instances
     *
     * @param PDO $db a PDO Database instance
     * @param AlaniaUsuarioModel $example an example instance defining the conditions. All non-null properties will be considered a constraint, null values will be ignored.
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaUsuarioModel[]
     */
    public static function findByExample(PDO $db, AlaniaUsuarioModel $example, $and = true, $sort = null) {
        $exampleValues = $example->toArray();
        $filter = array();
        foreach ($exampleValues as $fieldId => $value) {
            if (null !== $value) {
                $filter[$fieldId] = $value;
            }
        }
        return self::findByFilter($db, $filter, $and, $sort);
    }

    /**
     * Query by filter.
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * Will return matched rows as an array of AlaniaUsuarioModel instances.
     *
     * @param PDO $db a PDO Database instance
     * @param array $filter array of DFC instances defining the conditions
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaUsuarioModel[]
     */
    public static function findByFilter(PDO $db, $filter, $and = true, $sort = null) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        $sql = 'SELECT * FROM `alania_usuario`'
                . self::buildSqlWhere($filter, $and, false, true)
                . self::buildSqlOrderBy($sort);

        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        return self::fromStatement($stmt);
    }

    /**
     * Will execute the passed statement and return the result as an array of AlaniaUsuarioModel instances
     *
     * @param PDOStatement $stmt
     * @return AlaniaUsuarioModel[]
     */
    public static function fromStatement(PDOStatement $stmt) {
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        return self::fromExecutedStatement($stmt);
    }

    /**
     * returns the result as an array of AlaniaUsuarioModel instances without executing the passed statement
     *
     * @param PDOStatement $stmt
     * @return AlaniaUsuarioModel[]
     */
    public static function fromExecutedStatement(PDOStatement $stmt) {
        $resultInstances = array();
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $o = new AlaniaUsuarioModel();
            $o->assignByHash($result);
            $o->notifyPristine();
            $resultInstances[] = $o;
        }
        $stmt->closeCursor();
        return $resultInstances;
    }

    /**
     * Get sql WHERE part from filter.
     *
     * @param array $filter
     * @param bool $and
     * @param bool $fullyQualifiedNames true if field names should be qualified by table name
     * @param bool $prependWhere true if WHERE should be prepended to conditions
     * @return string
     */
    public static function buildSqlWhere($filter, $and, $fullyQualifiedNames = true, $prependWhere = false) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        return $filter->buildSqlWhere(new self::$CLASS_NAME, $fullyQualifiedNames, $prependWhere);
    }

    /**
     * get sql ORDER BY part from DSCs
     *
     * @param array $sort array of DSC instances
     * @return string
     */
    protected static function buildSqlOrderBy($sort) {
        return DSC::buildSqlOrderBy(new self::$CLASS_NAME, $sort);
    }

    /**
     * bind values from filter to statement
     *
     * @param PDOStatement $stmt
     * @param DFCInterface $filter
     */
    public static function bindValuesForFilter(PDOStatement &$stmt, DFCInterface $filter) {
        $filter->bindValuesForFilter(new self::$CLASS_NAME, $stmt);
    }

    /**
     * Execute select query and return matched rows as an array of AlaniaUsuarioModel instances.
     *
     * The query should of course be on the table for this entity class and return all fields.
     *
     * @param PDO $db a PDO Database instance
     * @param string $sql
     * @return AlaniaUsuarioModel[]
     */
    public static function findBySql(PDO $db, $sql) {
        $stmt = $db->query($sql);
        return self::fromExecutedStatement($stmt);
    }

    /**
     * Delete rows matching the filter
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * @param PDO $db
     * @param array $filter
     * @param bool $and
     * @return mixed
     */
    public static function deleteByFilter(PDO $db, $filter, $and = true) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        if (0 == count($filter)) {
            throw new InvalidArgumentException('refusing to delete without filter'); // just comment out this line if you are brave
        }
        $sql = 'DELETE FROM `alania_usuario`'
                . self::buildSqlWhere($filter, $and, false, true);
        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Assign values from array with the field id as index and the value as value
     *
     * @param array $array
     */
    public function assignByArray($array) {
        $result = array();
        foreach ($array as $fieldId => $value) {
            $result[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        $this->assignByHash($result);
    }

    /**
     * Assign values from hash where the indexes match the tables field names
     *
     * @param array $result
     */
    public function assignByHash($result) {
        $this->setIdUsuario($result['id_usuario']);
        $this->setIdentificacion($result['identificacion']);
        $this->setNombre($result['nombre']);
        $this->setApellido($result['apellido']);
        $this->setPassword($result['password']);
        $this->setSessionkey($result['sessionkey']);
        $this->setLastSeen($result['last_seen']);
        $this->setSexo($result['sexo']);
    }

    /**
     * Get element instance by it's primary key(s).
     * Will return null if no row was matched.
     *
     * @param PDO $db
     * @return AlaniaUsuarioModel
     */
    public static function findById(PDO $db, $idUsuario) {
        $stmt = self::prepareStatement($db, self::SQL_SELECT_PK);
        $stmt->bindValue(1, $idUsuario);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$result) {
            return null;
        }
        $o = new AlaniaUsuarioModel();
        $o->assignByHash($result);
        $o->notifyPristine();
        return $o;
    }

    /**
     * Bind all values to statement
     *
     * @param PDOStatement $stmt
     */
    protected function bindValues(PDOStatement &$stmt) {
        $stmt->bindValue(1, $this->getIdUsuario());
        $stmt->bindValue(2, $this->getIdentificacion());
        $stmt->bindValue(3, $this->getNombre());
        $stmt->bindValue(4, $this->getApellido());
        $stmt->bindValue(5, $this->getPassword());
        $stmt->bindValue(6, $this->getSessionkey());
        $stmt->bindValue(7, $this->getLastSeen());
        $stmt->bindValue(8, $this->getSexo());
    }

    /**
     * Insert this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function insertIntoDatabase(PDO $db) {
        if (null === $this->getIdUsuario()) {
            $stmt = self::prepareStatement($db, self::SQL_INSERT_AUTOINCREMENT);
            $stmt->bindValue(1, $this->getIdentificacion());
            $stmt->bindValue(2, $this->getNombre());
            $stmt->bindValue(3, $this->getApellido());
            $stmt->bindValue(4, $this->getPassword());
            $stmt->bindValue(5, $this->getSessionkey());
            $stmt->bindValue(6, $this->getLastSeen());
            $stmt->bindValue(7, $this->getSexo());
        } else {
            $stmt = self::prepareStatement($db, self::SQL_INSERT);
            $this->bindValues($stmt);
        }
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $lastInsertId = $db->lastInsertId();
        if (false !== $lastInsertId) {
            $this->setIdUsuario($lastInsertId);
        }
        $stmt->closeCursor();
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Update this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateToDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_UPDATE);
        $this->bindValues($stmt);
        $stmt->bindValue(9, $this->getIdUsuario());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Delete this instance from the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function deleteFromDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_DELETE_PK);
        $stmt->bindValue(1, $this->getIdUsuario());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Fetch AlaniaInformacionModel's which this AlaniaUsuarioModel references.
     * `alania_usuario`.`id_usuario` -> `alania_informacion`.`usuario_generador`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaInformacionModel[]
     */
    public function fetchAlaniaInformacionModelCollection(PDO $db, $sort = null) {
        $filter = array(AlaniaInformacionModel::FIELD_USUARIO_GENERADOR => $this->getIdUsuario());
        return AlaniaInformacionModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch AlaniaLogModel's which this AlaniaUsuarioModel references.
     * `alania_usuario`.`id_usuario` -> `alania_log`.`usuario`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaLogModel[]
     */
    public function fetchAlaniaLogModelCollection(PDO $db, $sort = null) {
        $filter = array(AlaniaLogModel::FIELD_USUARIO => $this->getIdUsuario());
        return AlaniaLogModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch PerfilDependenciaUsuarioModel's which this AlaniaUsuarioModel references.
     * `alania_usuario`.`id_usuario` -> `perfil_dependencia_usuario`.`alania_usuario_id_usuario`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return PerfilDependenciaUsuarioModel[]
     */
    public function fetchPerfilDependenciaUsuarioModelCollection(PDO $db, $sort = null) {
        $filter = array(PerfilDependenciaUsuarioModel::FIELD_ALANIA_USUARIO_ID_USUARIO => $this->getIdUsuario());
        return PerfilDependenciaUsuarioModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch PermisosInformacionUsuarioModel's which this AlaniaUsuarioModel references.
     * `alania_usuario`.`id_usuario` -> `permisos_informacion_usuario`.`usuario`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return PermisosInformacionUsuarioModel[]
     */
    public function fetchPermisosInformacionUsuarioModelCollection(PDO $db, $sort = null) {
        $filter = array(PermisosInformacionUsuarioModel::FIELD_USUARIO => $this->getIdUsuario());
        return PermisosInformacionUsuarioModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * return array with the property name as index and the field value as value.
     * ezComponents support method
     *
     * @return array
     */
    public function getState() {
        $array = $this->toArray();
        $state = array();
        foreach ($array as $fieldId => $value) {
            $state[self::$PROPERTY_NAMES[$fieldId]] = $value;
        }
        return $state;
    }

    /**
     * Assign values from hash where the indexes match the property names.
     * ezComponents support method
     *
     * @param array $state
     */
    public function setState(array $state) {
        $propertyNameToFieldId = array_flip(self::$PROPERTY_NAMES);
        $hash = $this->toHash();
        foreach ($state as $propertyName => $value) {
            $hash[self::$FIELD_NAMES[$propertyNameToFieldId[$propertyName]]] = $value;
        }
        $this->assignByHash($hash);
    }

    /**
     * get persistence definition for ezComponents
     *
     * @return ezcPersistentObjectDefinition
     */
    public static function toEzcPersistentObjectDefinition() {
        static $typeMapping = array(
    Db2PhpEntity::PHP_TYPE_BOOL => ezcPersistentObjectProperty::PHP_TYPE_BOOL,
    Db2PhpEntity::PHP_TYPE_INT => ezcPersistentObjectProperty::PHP_TYPE_INT,
    Db2PhpEntity::PHP_TYPE_FLOAT => ezcPersistentObjectProperty::PHP_TYPE_FLOAT,
    Db2PhpEntity::PHP_TYPE_STRING => ezcPersistentObjectProperty::PHP_TYPE_STRING
        );
        $def = new ezcPersistentObjectDefinition();
        $def->table = self::SQL_TABLE_NAME;
        $def->class = 'AlaniaUsuarioModel';
        if (!empty(self::$PRIMARY_KEYS)) {
            $pkField = self::$PRIMARY_KEYS[0];
            $def->idProperty = new ezcPersistentObjectIdProperty();
            $def->idProperty->columnName = self::$FIELD_NAMES[$pkField];
            $def->idProperty->propertyName = self::$PROPERTY_NAMES[$pkField];
            $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
                    in_array($pkField, self::$AUTOINCREMENT_FIELDS) ? 'ezcPersistentNativeGenerator' : 'ezcPersistentManualGenerator');
        } else {
            $pkField = null;
        }
        foreach (self::$PROPERTY_NAMES as $fieldId => $propertyName) {
            if ($fieldId !== $pkField) {
                $def->properties[$propertyName] = new ezcPersistentObjectProperty();
                $def->properties[$propertyName]->columnName = self::$FIELD_NAMES[$fieldId];
                $def->properties[$propertyName]->propertyName = $propertyName;
                $def->properties[$propertyName]->propertyType = $typeMapping[self::$PROPERTY_TYPES[$fieldId]];
            }
        }
        return $def;
    }

    /**
     * get element as DOM Document
     *
     * @return DOMDocument
     */
    public function toDOM() {
        return self::hashToDomDocument($this->toHash(), 'AlaniaUsuarioModel');
    }

    /**
     * get single AlaniaUsuarioModel instance from a DOMElement
     *
     * @param DOMElement $node
     * @return AlaniaUsuarioModel
     */
    public static function fromDOMElement(DOMElement $node) {
        $o = new AlaniaUsuarioModel();
        $o->assignByHash(self::domNodeToHash($node, self::$FIELD_NAMES, self::$DEFAULT_VALUES, self::$FIELD_TYPES));
        $o->notifyPristine();
        return $o;
    }

    /**
     * get all instances of AlaniaUsuarioModel from the passed DOMDocument
     *
     * @param DOMDocument $doc
     * @return AlaniaUsuarioModel[]
     */
    public static function fromDOMDocument(DOMDocument $doc) {
        $instances = array();
        foreach ($doc->getElementsByTagName('AlaniaUsuarioModel') as $node) {
            $instances[] = self::fromDOMElement($node);
        }
        return $instances;
    }

}

?>